﻿using UnityEngine;
using UnityEngine.InputSystem;

namespace Assets.Scripts
{
    public class RigidbodyController:MonoBehaviour
    {
        private Rigidbody _rb;
        private Animator _animator;
        [SerializeField] private Transform _target;

        [SerializeField] private float _rotateSpeed;

        private Vector3 _direction;

        private Vector2 _moveInput;
        [SerializeField]private float _moveSpeed;

        private void Start()
        {
            _rb = GetComponent<Rigidbody>();
            _animator = GetComponent<Animator>();
        }

        public void Rotate(Vector3 direction)
        {
            direction.y = 0;
            Vector3 targetForward = Vector3.RotateTowards(transform.forward, direction.normalized, _rotateSpeed * Time.deltaTime,.01f);
            Quaternion newRotation = Quaternion.LookRotation(targetForward);
            transform.rotation = newRotation;
        }

        public void Move(Vector3 direction)
        {
            direction.Normalize();
            Vector3 targetPosition = _rb.position + direction * _moveSpeed * Time.deltaTime;
            Vector3 targetVelocity = (targetPosition - transform.position) / Time.deltaTime;
            _rb.velocity = new Vector3(targetVelocity.x,_rb.velocity.y,targetVelocity.z);
        }

        #region 输入
        public void MoveInput(InputAction.CallbackContext ctx)
        {
            _moveInput = ctx.ReadValue<Vector2>();
        }
        #endregion

        

        private void FixedUpdate()
        {
            
            //_direction = _target.position - transform.position;
            _direction=new Vector3(_moveInput.x, 0, _moveInput.y);
            Rotate(_direction.normalized);
            Move(_direction.normalized);
            _animator.SetFloat("VerticalSpeed", _direction.magnitude*_moveSpeed);
        }
    }

}
